package com.skillworld.webapp.web.pages.rest.user;

import java.util.List;

import org.apache.tapestry5.annotations.ContentType;
import org.apache.tapestry5.annotations.Property;
import org.apache.tapestry5.annotations.SessionState;
import org.apache.tapestry5.ioc.annotations.Inject;
import org.apache.tapestry5.services.Request;

import com.skillworld.webapp.model.team.Team;
import com.skillworld.webapp.model.userservice.UserService;
import com.skillworld.webapp.model.util.Pagination;
import com.skillworld.webapp.web.util.ErrorMessages;
import com.skillworld.webapp.web.util.UserSession;

@ContentType("text/xml")
public class SearchTeams 
{
    private static final int DEFAULT_PAGE_SIZE = 20;
    private static final int DEFAULT_PAGE_NUMBER = 1;
   
    @SuppressWarnings("unused")
    @Property
    private String errorMessage = null;
    
    private int page;
    private int pageSize;
    
    @SuppressWarnings("unused")
    @Property
    private List<Team> teams;
    
    @SuppressWarnings("unused")
    @Property
    private Team team;   // loop iterator
    
    @Property
    private Pagination pagination;
    
    @Inject
    private UserService userService;

    @SessionState(create=false)
    private UserSession userSession;
    
    private boolean userSessionExists;

    @Inject
    private Request request;
   

    void onPassivate() 
    {
        return;
    }
    
    void onActivate()
    {
        if (!userSessionExists)
        {
            errorMessage = ErrorMessages.NOT_LOGGED_IN;
            return;
        }
        
        String query = request.getParameter("q");
        String pageParam = request.getParameter("page");
        String psizeParam = request.getParameter("psize");
        
        if (query == null)
        {
            errorMessage = ErrorMessages.INVALID_ARGUMENTS;
            return;
        }
        
        try
        {
            page = (pageParam == null)
                    ? DEFAULT_PAGE_NUMBER
                    : Integer.parseInt(pageParam);
            pageSize = (psizeParam == null)
                        ? DEFAULT_PAGE_SIZE
                        : Integer.parseInt(psizeParam);
            
            pagination = new Pagination(userService.numberOfTeams(query), 
                                            pageSize, page);
            
            if (pageSize <= 0 || !pagination.isValidPage())
            {
                errorMessage = ErrorMessages.INVALID_ARGUMENTS;
                return;
            }
            
            teams = userService.searchTeams(query, pagination.getStartIndex(), 
                                                   pagination.getCount());
        }
        catch (NumberFormatException e)
        { errorMessage = ErrorMessages.INVALID_ARGUMENTS; }
    }
}